<?php

// TODO need methods: write, del, add etc (pour editer les fichiers lang)
// TODO : count vars language, and loaded language files for debug

namespace framework\config;

use framework\Config;
use framework\utility\Tools;
use framework\Logger;

class Language extends Config {

    protected $_filename = null;
    protected $_format = null;
    protected $_defaultLanguageVars = array();

    public function __construct($filename, $format) {
        if (!file_exists($filename))
            throw new \Exception('File "' . $filename . '" don\'t exists');

        // Check format
        if ($format !== Config::XML && $format !== Config::INI)
            throw new \Exception('Invalid config format');

        $this->_filename = $filename;
        $this->_format = $format;
    }

    public function load($isLanguageDefault = false) {
        switch ($this->_format) {
            case self::XML:
                $xml = @simplexml_load_file($this->_filename);
                if ($xml === null || $xml === false)
                    throw new \Exception('Invalid xml file');


                if (!$isLanguageDefault)//preserve defaults vars
                    $this->_defaultLanguageVars = self::$_languageVars;
                //reset vars
                self::$_languageVars = new \stdClass();
                foreach ($xml as $varName => $varValue) {
                    //cast value
                    $varValue = Tools::castValue((string) $varValue);
                    if (method_exists(self::$_languageVars, $varName))
                        throw new \Exception('language var already defined');

                    //put on vars
                    self::$_languageVars->$varName = $varValue;
                }
                //Check if alls vars defined
                if (!$isLanguageDefault) {
                    foreach ($this->_defaultLanguageVars as $name => $value) {
                        if (!property_exists(self::$_languageVars, $name)) {
                            // Notify
                            Logger::getInstance()->debug('Miss language var : "' . $name . '" on new language file : "' . $this->_filename . '"');
                            // And add default language var
                            self::$_languageVars->$name = $this->_defaultLanguageVars->$name;
                        }
                    }
                }
                break;
            case self::INI:
                throw new \Exception('NOT YET');
                break;
            default:
                throw new \Exception('Config format must be setted');
                break;
        }
    }

}

?>